package net.seabookchen.view;

import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.seabookchen.pojo.linkedin.LinkedInPerson;

import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import com.google.gson.Gson;

public class JsonView extends MappingJacksonJsonView {
	private Gson gson = new Gson();

	@Override
	protected void renderMergedOutputModel(Map<String, Object> model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String size = (String) model.get("totalSize");
		LinkedInPerson resume = (LinkedInPerson) model.get("resume");
		List<Object> entities = (List<Object>) model.get("entities");
		String json = null;
		if (entities != null && entities.size() > 0)
			json = gson.toJson(entities);
		else if (size != null && size.length() > 0) {
			json = "{\"totalSize\":" + size + "}";
		} else if (resume != null ) {
			json = gson.toJson(resume);
		} else
			throw new RuntimeException("Json can't be built!!! " + json);
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.write(json.toString());
		} finally {
			if (writer != null) writer.close();
		}
		
	}

}
